package leetcode.lt100;

import java.util.ArrayList;
import java.util.List;

class Solution_51 {
	public List<List<String>> solveNQueens(int n) {
		List<List<String>> res = new ArrayList<>();
		int[] board = new int[n];
		dfs(res, board, 0);
		return res;
	}

	private void dfs(List<List<String>> res, int[] board, int depth) {
		int n = board.length;
		if (depth == n) {
			res.add(board2List(board));
			return;
		}
		for (int i = 0; i < n; i++) {
			if (check(board, depth, i)) {
				board[depth] = i;
				dfs(res, board, depth + 1);
			}
		}
	}

	private List<String> board2List(int[] board) {
		List<String> list = new ArrayList<>();
		int n = board.length;
		for (int i = 0; i < n; i++) {
			int num = board[i];
			StringBuffer sb = new StringBuffer();
			for (int j = 0; j < n; j++) {
				sb.append(j == num ? "Q" : ".");
			}
			list.add(sb.toString());
		}
		return list;
	}

	private boolean check(int[] board, int depth, int num) {
		for (int i = 0; i < depth; i++) {
			if (board[i] == num || Math.abs(depth - i) == Math.abs(num - board[i]))
				return false;
		}
		return true;
	}
}